/*
@Time : 2021/2/19 17:19
@Author : 吴周海
@Mail: wzh200x@126.com
@File : PayCallBack.go
@Software: GoLand
*/
package controllers

import (
	"GameApiServer/backData"
	"GameApiServer/function"
	"GameApiServer/models"
	"GameApiServer/requestData"
	"GameApiServer/utils"
	"encoding/json"
	beego "github.com/beego/beego/v2/adapter"
	"strconv"
	"time"
)

type PayCallBackController struct {
	beego.Controller
}

func (this *PayCallBackController) Get() {
	p := requestData.PayBackData{}
	b := &backData.NormalBackData{
		Code: 0,
		Info: "",
		Ext:  "",
	}
	// 解析数据
	if err := this.ParseForm(&p); err != nil {
		b.Code = backData.BACK_REQUEST_DATA_ERROR
		jData, jErr := json.Marshal(b)
		if jErr != nil {
			this.Ctx.Output.Body(jData)
			return
		}
	}
	// 开始处理
	// 验证数据
	if checkResult := utils.VerifyRequestData(&p); checkResult != true {
		b.Code = backData.BACK_VERIFY_FAILED
		jData, jErr := json.Marshal(b)
		if jErr != nil {
			this.Ctx.Output.Body(jData)
			return
		}
	}
	// 判断时间
	rTime, err := strconv.ParseInt(p.RequestTime, 10, 64)
	if err != nil {
		b.Code = backData.BACK_PARSETIME_FAILED
		jData, jErr := json.Marshal(b)
		if jErr != nil {
			this.Ctx.Output.Body(jData)
			return
		}
	}
	// 超过5分钟的订单不再处理
	if time.Now().Unix()-rTime > 300 {
		b.Code = backData.BACK_TIMEOUT
		jData, jErr := json.Marshal(b)
		if jErr == nil {
			this.Ctx.Output.Body(jData)
			return
		}
	}
	// 创建订单数据库对象
	dp := models.NewPayRecordInfo(&p)
	// 保存请求的IP
	dp.Ip = this.Ctx.Request.RemoteAddr
	// 判断订单是否存在,存入数据库
	// 订单已经存在
	if dp.CheckIsExist() == true {
		b.Code = backData.BACK_PAY_ORDER_EXIST
		jData, jErr := json.Marshal(b)
		if jErr == nil {
			this.Ctx.Output.Body(jData)
			return
		}
	}
	// 执行充值操作,通知游戏服务器
	// 充值成功,修改标识
	if function.NoticeServerPay(dp) == true {
		dp.UpdatePayStatus()
	} else { // 充值失败,记录原因,将失败订单信息放到补单列表中
		function.ServerPayFailed(dp)
	}
	jData, jErr := json.Marshal(b)
	if jErr == nil {
		this.Ctx.Output.Body(jData)
		return
	}
}
